<?php
namespace common\services;

use common\models\UserHistory;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;

class UserHistoryServices extends UserHistory
{

    /**
     * 用户浏览记录积分查询
     * @param $params
     * @return array
     */
    public function search($params){
        $model = UserHistory::find(false);
        $model->orderBy('id desc');

        if (!empty($params['user_id'])) {
            $model->andFilterWhere(['=', 'user_id', $params['user_id']]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['object_type']) && $params['object_type'] != '') {
            $model->andFilterWhere(['=', 'object_type', $params['object_type']]);
        }

        if (isset($params['status']) && $params['status'] != '') {
            $model->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or', ['like', 'object_id', $params['keywords']], ['like', 'user_id', $params['keywords']]]);
        }

        return $dataProvider;
    }

    /**
     * 添加记录
     * @param $objectType
     * @param $objectId
     * @param string $userId
     */
    public function addRecord($objectType, $objectId, $userId = ''){
        $sessId = session_id();
        $find = UserHistory::find(false)->andFilterWhere(['object_type' => $objectType, 'object_id' => $objectId, 'user_id' => $userId, 'sess_id' => $sessId])->one();
        if (empty($find)) {
            $model = new UserHistory();
            $model->object_type = $objectType;
            $model->object_id = $objectId;
            $model->user_id = $userId;
            $model->sess_id = $sessId;
            $model->save();
        }else{
            $find->views_number = $find->views_number + 1;
            $find->update();
        }
    }

    /**
     * 获取用户浏览记录
     * @param null $objectType
     * @param string $userId
     */
    public function getUserInterestByUserId($objectType = null, $userId = '') {
        $model = UserHistory::find(false);
        $model->andFilterWhere(['=', 'status', UserHistory::STATUS_FLAG_NORMAL]);
        if (!is_null($objectType)) {
            $model->andFilterWhere(['=', 'object_type', $objectType]);
        }
        if (!empty($userId)) {
            $model->andFilterWhere(['=', 'user_id', $userId]);
        }else{
            $sess_id = session_id();
            $model->andFilterWhere(['=', 'sess_id', $sess_id]);
        }
        $res = $model->orderBy('views_number desc,updated_at desc')->groupBy("object_id")->asArray()->all();
        return $res;
    }

}
